package com.kfm.exec;

public class Test02 {

    public static void main(String[] args) {
        Book[] books = new Book[5];
        books[0] = new Book("PHP", 5);
        books[1] = new Book("Java", 1);
        books[2] = new Book("C", 4);
        books[3] = new Book("Python", 3);
        books[4] = new Book("C++", 2);
        quickSort(books);
        for (Book book : books) {
            System.out.println(book);
        }
    }

    public static void quickSort(Book[] books) {
        quick(books, 0, books.length - 1);
    }

    private static void quick(Book[] books, int left, int right) {
        if (left >= right) {
            return;
        }
        int i = left;
        int j = right;
        Book temp = books[left];
        while (i != j) {
            // 从右往左找比基准值小的停下来
            while (i < j && books[j].getNo() >= temp.getNo()) {
                j--;
            }
            // 从左往右找比基准值大的停下来
            while (i < j && books[i].getNo() <= temp.getNo()) {
                i++;
            }
            if (i < j) {
                Book t = books[i];
                books[i] = books[j];
                books[j] = t;
            }
        }
        // 与基准值交换位置
        if (temp.getNo() > books[i].getNo()) {
            books[left] = books[i];
            books[i] = temp;
        }
        // 排序左边
        quick(books, left, i - 1);
        // 排序右边
        quick(books, i + 1, right);
    }
}
